package com.lhcai.haweiOD;

/**
 * @author lhcstart
 * @create 2023-03-02 9:23
 */

import javax.swing.plaf.nimbus.NimbusLookAndFeel;
import java.awt.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
import java.util.logging.Level;

/**
 * 某点到各个区域最小值
 * 给出找出服务中心该建立的位置到各个区域距离最小值
 * 给出各个区域[left, right]位置，left,right均属于[-1e9, 1e9]，区域数量1e5
 * <p>
 * 找一个点建立服务中心位置，返回服务中心到各个区域距离的最小值
 * <p>
 * 距离求法：服务中心n点，n > right，则为n - right，n < left时 则为left - n，服务中心再区域内时距离为0
 */
public class HJ222 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {

            int n = sc.nextInt();
            int[][] areas = new int[n][2];

            for (int i = 0; i < n; i++) {
                areas[i][0] = sc.nextInt();
                areas[i][1] = sc.nextInt();
            }

//            Arrays.sort(areas, Comparator.comparingInt(o -> o[0]));

            int minl = Integer.MAX_VALUE, maxl = Integer.MIN_VALUE;
            for (int i = 0; i < n; i++) {
                minl = Math.min(minl, areas[i][0]);
                maxl = Math.min(maxl, areas[i][1]);
            }

            int l = minl, r = maxl;
            long res = Long.MAX_VALUE;

            while (l < r) {
                int mid = (l + r + 1) >> 1;
                long[] distance = getDistance(areas, mid);

                long d0 = distance[0], d1 = distance[1];
                if (d0 == d1) {
                    System.out.println(d0);
                    return;
                }
                if (d0 < d1) {
                    r = mid;
                } else {
                    l = mid + 1;
                }
                res = Math.min(d0, d1);
            }
            System.out.println(res);
        }
    }

    // 返回x点到各个区域距离与x+1点到各个区域距离
    private static long[] getDistance(int[][] areas, int x) {

        long[] distance = new long[2];
        for (int[] area : areas) {
            int l = area[0], r = area[1];
            if (x < l) {
                distance[0] += l - x;
            } else if (x > r) {
                distance[0] += x - r;
            }

            if (x + 1 < l) {
                distance[1] += (l - (x + 1));
            } else if (x + 1 > r) {
                distance[1] += (x + 1 - r);
            }
        }
        return distance;
    }
}
